package edu.fub.pub2search.app.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JavaTypeMapper;

/**
 * An utility class that manage JSON parsing.
 * 
 * @author Josef
 */
public class JSONUtil {
	
	/**
	 * Convert Map<String, String>[] to JSON string.
     * This code snippet is taken from: 
     * <a>http://twit88.com/blog/wp-content/uploads/2008/10/jsonutil.java</a>
     * 
	 * @param list An array of Map object.
	 * @return A JSON string.
	 */
	public static String getJsonStringFromList(List<Map<String, String>> list) {
    	
    	JsonFactory jf = new JsonFactory();
    	try {
            StringWriter sw = new StringWriter();
            JsonGenerator gen = jf.createJsonGenerator(sw);
            new JavaTypeMapper().writeValue(gen, list);
            gen.flush();
            return sw.toString();
        } catch (Exception e) {
            return null;
        }
    }
	
	/**
	 * Convert JSON string to Map<String, String>[].
     * This code snippet is taken from: 
     * <a>http://twit88.com/blog/wp-content/uploads/2008/10/jsonutil.java</a>
     * 
	 * @param str A JSON string
	 * @return An array of Map object.
	 */
    public static List<Map<String, String>> getListFromJsonString(String str) {
   	 JsonFactory jf = new JsonFactory();
   	 
        try {
            if (StringUtils.isNotBlank(str)) {
        		JsonParser parser = jf.createJsonParser(new StringReader(str));
           	 
                ArrayList<Map<String, String>> arrList = 
                	(ArrayList<Map<String, String>>) new JavaTypeMapper().read(parser);
                return arrList;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
}
